from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime as dt
import datetime
from google.appengine.api import users
from models.ChiTieuKinhDoanh import ChiTieuKinhDoanh
from utils.Const import LoaiNhanVien
from utils.permission_required import permission_required
import WSGI
import json as simplejson
import logging
import math
import webapp2

logger = logging.getLogger("GUIChiTieuKinhDoanh")

class GUIHomePage(webapp2.RequestHandler):
    def get(self):
        if users is None or users.get_current_user() is None:
            self.redirect(users.create_login_url(self.request.uri))
            return
        username = users.get_current_user().nickname()
        if username is None:
            self.redirect(users.create_login_url(self.request.uri))
            return
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        if nv is None:
            self.redirect('/error/')
            return
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
#        if nv.loaiNV == LoaiNhanVien.QUAN_LY:
#            self.redirect('/quanlynhanvien/')
#        elif nv.loaiNV == LoaiNhanVien.KINH_DOANH:
#            self.redirect('/quanlydonhang/')
        if str(nv.codeLoaiNV) == str(LoaiNhanVien.TRUONG_CA_SAN_XUAT) or str(nv.codeLoaiNV) == str(LoaiNhanVien.XUONG):
            self.redirect('/hangsanxuathomnay/')
#        elif nv.loaiNV == LoaiNhanVien.KE_TOAN:
#            self.redirect('/quanlycongno/')
#        elif nv.loaiNV == LoaiNhanVien.QUAN_LY_GIAO_HANG:
#            self.redirect('/quanlydonhang/')
        else:
            self.redirect('/quanlydonhang/')
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/Home.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListChiTieuKinhDoanh': 'getListChiTieuKinhDoanh',
                       'updateChiTieuKinhDoanh': 'updateChiTieuKinhDoanh'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListChiTieuKinhDoanh(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maNV = self.request.get('maNV')
        thang = self.request.get('thang')
        nam = self.request.get('nam')
        rows, rowNum = DaoQuanLyNhanVien.getListChiTieuKinhDoanh(maNV, thang, nam, gridRowNum, int((pageNum-1)*gridRowNum))
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateChiTieuKinhDoanh(self):
        id = self.request.get('id')
        now = dt.now() + datetime.timedelta(hours=7)
        if id != '_empty':
            ctkd = ChiTieuKinhDoanh.get_by_id(int(id))
        else:
            ctkd = ChiTieuKinhDoanh()
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper == 'del':
            if ctkd.nam <= now.year and ctkd.thang < now.month:
                return 0
            DaoQuanLyNhanVien.deleteChiTieuKinhDoanh(ctkd)
            return 1
        else:
            thang = int(self.request.get('thang'))
            nam = int(self.request.get('nam'))
            if nam <= now.year and thang < now.month:
                return 0
            ctkd.maNV = int(self.request.get('tenNV'))
            ctkd.tenNV = DaoQuanLyNhanVien.getNhanVienById(ctkd.maNV).tenNV
            ctkd.thang = thang
            ctkd.nam = nam
            ctkd.doanhSo = int(self.request.get('doanhSo'))
            
            DaoQuanLyNhanVien.createOrUpdateChiTieuKinhDoanh(ctkd)
            return 1
        
        
            
        